import Vue from 'vue'
import VueRouter from 'vue-router'
import Films from '@/views/Films.vue'
import Nowplaying from '@/views/films/Nowplaying.vue'
import Comingsoon from '@/views/films/Comingsoon.vue'
import Detail from '@/views/Detail.vue'
import Cinemas from '@/views/Cinemas.vue'
import City from '@/views/City.vue'
import Search from '@/views/Search.vue'
// import Center from '@/views/Center.vue'
// import Order from '@/views/Order.vue'
import Login from '@/views/Login.vue'

Vue.use(VueRouter) // 注册使用路由插件

// 当加载某个页面时 路由会帮助加载组件 跳转页面
// 配置表
const routes = [
  {
    path: '/films',
    component: Films,
    // 嵌套路由
    children: [
      {
        path: '/films/nowplaying',
        component: Nowplaying
      },
      {
        path: '/films/comingsoon',
        component: Comingsoon
      },
      {
        path: '/films',
        redirect: '/films/nowplaying',
      }
    ]
  },
  {
    path: '/detail/:id', //动态路由 动态二级路由
    component: Detail
  },
  {
    path: '/cinemas',
    component: Cinemas
	},
	{
		path: '/city',
		component: City
	 },
  {
    path: '/cinemas/search',
    component: Search
  },
  {
    path: '/center',
    // 懒加载我的页面
    component: ()=> import('@/views/Center.vue'),
    meta: {
      isRequired: true
    },
    // 路由独享拦截方式
    // beforeEnter: (to, from, next) => {
    //   // ...
    //   if (localStorage.getItem()) {
    //     next()
    //   } else {
    //     next('/login')
    //   }
    // }
  },
  {
    path: '/order',
    // 懒加载订单页面
    component: ()=>import('@/views/Order.vue'),
    meta: {
      isRequired: true
    }
  },
  {
    path: '/login',
    component: Login
  },
  // 重定向
  {
    path: '*',
    redirect: '/films'
  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})

// 全局拦截
router.beforeEach((to,from,next) => {
  // console.log(to);

  if (to.meta.isRequired) {
    // 判断 本地存储中是否token
    if (localStorage.getItem('token')) {
      next()
    } else {
      next({
        path: '/login',
        query: {redirect: to.fullPath}
      })
    }
  } else {
    next()
  }
})

export default router
